import logging
import urllib2
from RegModel import RegModel
from weibo import APIClient
from weibo import APIError

class WeiboAuth(object):
    def __init__(self,app_key='1112253491',app_secret='74c666655896ca1faad62da501435b51',
                 url='http://talkgtalk.sinaapp.com/callback.php',sender=None):
        self.App_key = app_key
        self.App_secret = app_secret
        self.Url = url
        self.sender = None

    def store_auth(self,sender,code):
        regInfo = RegModel(key_name=sender)
        client = APIClient(self.App_key,self.App_secret, redirect_uri=self.Url)
        try:
            token = client.request_access_token(code,self.Url)
            client.set_access_token(token.access_token, token.expires_in)
            regInfo.sender=self.sender
            regInfo.access_token = token.access_token
            regInfo.expires_in = token.expires_in
            regInfo.uid = str(token.uid)
            regInfo.put()
        except APIError as apierr:
            print str(apierr)
        except urllib2.HTTPError as err:
            print str(err)   # 记录HTTP状态码
            print err.read() # 同时记录错误代码

